package jp.co.cos.ittrick.channel.common.filter;

import java.io.IOException;
import java.text.SimpleDateFormat;
import java.util.Calendar;
import java.util.Enumeration;
import java.util.logging.Logger;

import javax.servlet.Filter;
import javax.servlet.FilterChain;
import javax.servlet.FilterConfig;
import javax.servlet.ServletException;
import javax.servlet.ServletRequest;
import javax.servlet.ServletResponse;
import javax.servlet.http.HttpServletRequest;

public class AccessFilter implements Filter {

	@Override
	public void init(FilterConfig arg0) throws ServletException {}

	@SuppressWarnings({"rawtypes" })
    @Override
	public void doFilter(ServletRequest request, ServletResponse Response,
			FilterChain chain) throws IOException, ServletException {

		Logger logger = Logger.getLogger(this.getClass().getName());

		// リクエスト
		HttpServletRequest req = (HttpServletRequest)request;

		// 日本時間に変更するため、現在のタイムスタンプ + 9時間する
		Calendar calendar = Calendar.getInstance();
		calendar.add(Calendar.HOUR, 9);
		SimpleDateFormat sdf = new SimpleDateFormat(
				"yyyy'年'MM'月'dd'日' HH'時'mm'分'ss'秒'");

		// 日本時間の出力
		StringBuffer sb = new StringBuffer();
		sb.append("\n");
		sb.append("【日本時間】：" + sdf.format(calendar.getTime()));
		sb.append("\n");

		// ヘッダーの数だけ繰り返す
		Enumeration headernames = req.getHeaderNames();
	    while (headernames.hasMoreElements()){
	      String name = (String)headernames.nextElement();
	      Enumeration headervals = req.getHeaders(name);
	      while (headervals.hasMoreElements()){
	        String val = (String)headervals.nextElement();
	        sb.append("【" + name + "】");
	        sb.append(" :   ");
	        sb.append(val);
	        sb.append("\n");
	      }
	    }

	    logger.info(sb.toString());

	    chain.doFilter(request, Response);

	}

	@Override
	public void destroy() {}

}
